package area;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

import network.NetworkCell;
import network.NetworkMap;

import org.gps.utils.LatLonPoint;
import org.gps.utils.LatLonUtils;

import utils.Logger;
import visual.Kml;



public class Placemark {
	
	public static final Placemark STADIO_OLIMPICO_TO = new Placemark("Stadio Olimpico (TO)", new double[]{45.041644,7.650003}, 100);
	public static final Placemark JUVE_STADIUM_TO = new Placemark("Juventus Stadium (TO)", new double[]{45.109536,7.641453}, 100);
	public static final Placemark STADIO_SILVIO_PIOLA_NO = new Placemark("Stadio Silvio Piola (NO)", new double[]{45.435804,8.595901}, 100);
	public static final Placemark MOLE_TO = new Placemark("Mole (TO)", new double[]{45.070588,7.693485}, 500);
	
	public String name;
	public double[] center;
	public LatLonPoint center_point;
	public double radius;
	private Set<String> cellsAround;
	
	public Placemark(String name, double[] point, double radius) {
		this.name = name;
		this.center = point;
		center_point = new LatLonPoint(center[0],center[1]);
		this.radius = radius;
		this.cellsAround = getCellsAround();
	}
	
	
	private Set<String> getCellsAround() { 
		Set<String> cellsAround = new HashSet<String>();
		NetworkMap nm = NetworkMap.getInstance();
		double bbox = 1;
		double[] ll = new double[]{center[0]-bbox,center[1]-bbox};
		double[] tr = new double[]{center[0]+bbox,center[1]+bbox};
		Set<NetworkCell> ncells = nm.getCellsIn(ll, tr);
		for(NetworkCell nc: ncells) 
			if( (LatLonUtils.getHaversineDistance(nc.getPoint(),center_point) - nc.getRadius()) < radius )
				cellsAround.add(String.valueOf(nc.getCellac()));
		return cellsAround;
	}
	
	public boolean contains(long celllac) {
		return cellsAround.contains(String.valueOf(celllac));
	}
	
	public boolean contains(String celllac) {
		return cellsAround.contains(celllac);
	}
	
	public void printKML(String file) throws Exception {
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
		Kml kml = new Kml();
		String name = file.substring(file.lastIndexOf("/")+1,file.lastIndexOf("."));
		kml.printHeaderFolder(out, name);
		NetworkMap nm = NetworkMap.getInstance();
		for(String cell: cellsAround) 
			out.println(nm.get(Long.parseLong(cell)).toKml());
		kml.printFooterFolder(out);
		out.close();
	} 
	
	
	public static void main(String[] args) throws Exception {
		Placemark x = Placemark.STADIO_SILVIO_PIOLA_NO;
		x.printKML("output/"+x.name+".kml");
		Logger.logln("Done!");
	}
	
}
